package com.maple.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.maple.excel.entity.ExcelData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelExportController {

    @GetMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 模拟数据
        List<ExcelData> dataList = generateData();

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("export_data", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), ExcelData.class).sheet("Sheet1").doWrite(dataList);
    }

    private List<ExcelData> generateData() {
        // 这里可以从数据库或其他数据源获取数据
        List<ExcelData> dataList = new ArrayList<>();
        dataList.add(new ExcelData("John", 25));
        dataList.add(new ExcelData("Jane", 30));
        // 添加更多数据...

        return dataList;
    }
}
